/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.fzhucc.modules.pms.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.lesson.domain.dto.LessonQueryCriteria;
import com.fzhucc.modules.notice.domain.dto.NoticeQueryCriteria;
import com.fzhucc.modules.pms.domain.ProjectDesire;
import com.fzhucc.modules.pms.domain.dto.ProjectDesireDto;
import com.fzhucc.modules.pms.domain.dto.ProjectDesireQueryCriteria;
import com.fzhucc.modules.pms.repository.ProjectDesireRepository;
import com.fzhucc.modules.pms.service.mapstruct.ProjectDesireMapper;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Woolsen
* @date 2023-02-06
**/
@Service
@RequiredArgsConstructor
public class ProjectDesireService {

    private final ProjectDesireRepository projectDesireRepository;
    private final ProjectDesireMapper projectDesireMapper;

    private final UserRepository userRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    public Map<String,Object> queryAll(ProjectDesireQueryCriteria criteria, Pageable pageable){
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        Page<ProjectDesire> page = projectDesireRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(projectDesireMapper::toDto));
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(ProjectDesireQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null  && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                //不赋予则返回所有都能看
                return null;
            }
            if (res.getOrgArea().contains(";")) {
                String[] split = res.getOrgArea().split(";");
                if (split.length == 2) {
                    return split[1];
                } else if (split.length == 3) {
                    return split[1];
                } else if (split.length == 1) {
                    return split[0];
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            } else {
                throw new BadRequestException("未符合规范的地区区域");
            }
        }
    }

    public List<ProjectDesireDto> queryAll(ProjectDesireQueryCriteria criteria){
        if(criteria.getOrgArea()!=null && !criteria.getOrgArea().equals("")){
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)){
                criteria.setOrgArea(null);
            }
        }else{
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return projectDesireMapper.toDto(projectDesireRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    public ProjectDesireDto findById(Long id) {
        ProjectDesire projectDesire = projectDesireRepository.findById(id).orElseGet(ProjectDesire::new);
        ValidationUtil.isNull(projectDesire.getId(),"ProjectDesire","id",id);
        return projectDesireMapper.toDto(projectDesire);
    }

    @Transactional(rollbackFor = Exception.class)
    public ProjectDesireDto create(ProjectDesire resources) {
        resources.setOrgArea(orgAreaReturn());
        return projectDesireMapper.toDto(projectDesireRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(ProjectDesire resources) {
        ProjectDesire projectDesire = projectDesireRepository.findById(resources.getId()).orElseGet(ProjectDesire::new);
        ValidationUtil.isNull( projectDesire.getId(),"ProjectDesire","id",resources.getId());
        projectDesire.copy(resources);
        projectDesire.setOrgArea(orgAreaReturn());
        projectDesireRepository.save(projectDesire);
    }

    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            projectDesireRepository.deleteById(id);
        }
    }

    public void download(List<ProjectDesireDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProjectDesireDto projectDesire : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("创建人", projectDesire.getCreateBy());
            map.put("创建时间", projectDesire.getCreateTime());
            map.put("更新人", projectDesire.getUpdateBy());
            map.put("更新时间", projectDesire.getUpdateTime());
            map.put("联系方式", projectDesire.getContact());
            map.put("名字", projectDesire.getName());
            map.put("项目名称", projectDesire.getProject().getProjectName());
            map.put("区域划分", projectDesire.getOrgArea());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}